<template>
  <!-- <div class="wrapper">
    <Anchor :labelList="labels" activeId="row-01" labelWidth="130">
      <div class="line" id="row-01"> -->
          <div>
        <!-- 基本信息 -->
           <BreakSpace label="基本信息" :containerStyle="{ marginBottom: '10px' }" />
        <div>
          <FormPanel
            :list="initForm"
            :cols="3"
            :formType="type"
            :labelWidth="120"
            :isSubmitBtn="false"
            @formChange="formChangeHandle"
            class="mtop"
          />
        </div>
        <!-- 附件 -->
        <div style="position: relative;">
          <FormPanel
            ref="fileFormPanel"
            :list="fileForm"
            :cols="3"
            :labelWidth="70"
            :isSubmitBtn="false"
            @formChange="formChange"
            class="mtop"
          />
          <el-button
            @click="saveFile"
            style="position: absolute; top:0px; left:160px"
            type="primary"
          >保存附件</el-button>
        </div>
      <!-- </div>
      <div class="line" id="row-02">
        <div style="height:500px;"> -->
             <BreakSpace label="项目信息" :containerStyle="{ marginBottom: '10px' }" />
          <FormPanel
            :list="initForm2"
            :cols="2"
            :formType="type"
            :labelWidth="120"
            :isSubmitBtn="false"
            @formChange="formChangeHandle"
            class="mtop"
          />
        <!-- </div>
      </div>
      <div class="line" id="row-03">
        <div style="height:500px;"> -->
             <BreakSpace label="竞争对手分析" :containerStyle="{ marginBottom: '10px' }" />
          <FormPanel
            :list="initForm3"
            :cols="2"
            :formType="type"
            :labelWidth="120"
            :isSubmitBtn="false"
            @formChange="formChangeHandle"
            class="mtop"
          />
        <!-- </div>
      </div>
      <div class="line" id="row-04">
        <div style="height:500px;"> -->
          <!-- 编辑 -->
            <BreakSpace label="联系人信息" :containerStyle="{ marginBottom: '10px' }" />
          <BaseDialog
            :title="title"
            width="700px"
            destroyOnClose
            :visible.sync="visibleContactInfo"
            :containerStyle="{height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px'}"
          >
            <contactInfoDlg
              ref="contactInfoDlg"
              :rowData="formData"
              :type="handleType"
              @close="closeContactInfo"
            />
          </BaseDialog>

          <FilterTable
            ref="table"
            height="450"
            :columns="columns"
            :fetchapi="contactList"
            :params="fetchParams"
            :isSelectColumn="isSelectColumn"
            :datakey="'majorProjectContactList'"
            columnsRef='customerManage_continueManage_record_edit_01'
            :isPagination="isPagination"
            :onColumnsChange="columns => this.columns = columns"
          >
            <template slot="controls">
              <el-button size="small" type="primary" icon="el-icon-plus" @click="addHandle()">添加</el-button>
            </template>
          </FilterTable>
        <!-- </div>
      </div>
      <div class="line" id="row-05"> -->
         <BreakSpace label="意向车型需求信息" :containerStyle="{ marginBottom: '10px' }" />
        <CarInfo v-model="value" :infoBasic="infoType" />
      <!-- </div>
      <div class="line" id="row-06"> -->
          <BreakSpace label="跟进历史" :containerStyle="{ marginBottom: '10px' }" />
        <followInfo
          :projectFollowUpStatus="projectFollowUpStatus"
          :refreshfun="refreshfun"
          v-model="value"
          :infoBasic="infoType"
        />
      <!-- </div>
      <div class="line" id="row-07"> -->
            <BreakSpace label="战败\延续记录" :containerStyle="{ marginBottom: '10px' }" />
        <applyInfo
          v-model="value"
          :infoBasic="infoType"
          :projectFollowUpStatus="projectFollowUpStatus"
        />
      <!-- </div>
    </Anchor> -->
    <div
      :style="{
        position: 'absolute',
        left: 0,
        bottom: 0,
        right: 0,
        zIndex: 9,
        borderTop: '1px solid #e9e9e9',
        padding: '10px 20px',
        background: '#fff',
        textAlign: 'right'
      }"
    >
      <el-button @click="closeDialog">关 闭</el-button>
    </div>
  </div>
</template>

<script>
import { dictionary } from '@/utils/dictMixin';
import { authority } from '@/utils/authMixin';
import { region } from '@/api/cms-common/region'; //行政区域
import { propertyInfo } from '@/api/cms-api/customerManage/continueManage/record/index';
import { contactList } from '@/api/cms-api/customerManage/continueManage/record/index';
import { delcontact } from '@/api/cms-api/customerManage/continueManage/record/index';
import { updateFile } from '@/api/cms-api/customerManage/continueManage/record/index';
import { carInfo } from '@/api/cms-api/customerManage/continueManage/record/index';
import contactInfoDlg from '@/pages/cms-pages/customerManage/continueManage/record/contactEdit'; //编辑车辆
import CarInfo from './infoCar'; //意向车型需求信息
import applyInfo from './applyInfo'; //申请记录
import followInfo from './followInfo'; //跟进历史信息
import { formatdateByDay } from '@/utils/index';
export default {
  mixins: [dictionary, authority, region],
  components: {
    CarInfo,
    contactInfoDlg,
    followInfo,
    applyInfo
  },

  props: {
    rowData: {
      type: Object,
      default: () => ({})
    },
    infoType: {
      type: String,
      required: true
    }
  },

  data() {
    this.res = null;
    return {
      labels: [
        { title: '基本信息', id: 'row-01' },
        { title: '项目信息', id: 'row-02' },
        { title: '竞争对手分析', id: 'row-03' },
        { title: '联系人信息', id: 'row-04' },
        { title: '意向车型需求信息', id: 'row-05' },
        { title: '跟进历史', id: 'row-06' },
        { title: '战败/延续记录', id: 'row-07' }
      ],
      initForm: this.initFormFun(),
      initForm2: this.initFormFun2(),
      initForm3: this.initFormFun3(),
      fileForm: this.fileFormFun(),
      visibleContactInfo: false,
      fetchApi: propertyInfo, //ipa 接口
      contactList: contactList,
      type: 'show',
      isPagination: false,
      isSelectColumn: false,
      projectFollowUpStatus: this.rowData.projectFollowUpStatus,
      value: this.rowData.projectId,
      fetchParams: { projectId: this.rowData.projectId }, //参数
      projectId: this.rowData.projectId,
      columns: this.creatHeader(),
      dataSource: {},
      handleType: '',
      formData: {},
      formValue1: '',
      title: '',
      isLicenseAll:false // 全国上牌
    };
  },
  mounted() {
    //初始化省份
    this.initProvince();
    //this.initCity();
    //this.initTown();
    // this.saveDialog();
  },
  created() {
    this.saveDialog();
    //this.init();
    console.log(this.infoBasic);
  },
  watch: {
    isOk(newval, oldval) {
      if (newval) {
        this.init();
      }
    }
  },
  methods: {
    refreshfun() {
      //this.reloadInit();
      this.getComputedStatus();
      //this.initFormFun();
    },
    async getComputedStatus() {
      let re = await propertyInfo(this.rowData.projectId);
      this.initForm.find(item => item.fieldName === 'customerStatus').initialValue = re.data.customerStatus;
    },
    //初始化所在省份
    async initProvince() {
      let pl = await this.createRegionList();
      this.initForm[6].itemList = pl;
      this.initForm.find(item => item.fieldName === 'licenseProvinces').itemList = pl;
    },
    //初始化所在市数据
    async initCity(customerProvince) {
      if (!customerProvince || customerProvince == null || typeof customerProvince == 'undefined') {
        return;
      }
      //取省数据
      let rd = this.getRegionData();
      this.cityData = rd[customerProvince].children;
      let cl = this.createSubRegionList(this.cityData);
      this.initForm[7].itemList = cl;
      // this.initForm.find(item => item.fieldName === 'licenseCity').itemList = cl;
    },
    async initLicenseCity(licenseProvince) {
      console.log('licenseProvince', licenseProvince);
      if (!licenseProvince || licenseProvince == null || typeof licenseProvince == 'undefined') {
        return;
      }
      if(!this.isLicenseAll){
        //取省数据
        let rd = this.getRegionData();
        this.cityData = rd[licenseProvince].children;

        let cl = this.createSubRegionList(this.cityData);
        this.initForm.find(item => item.fieldName === 'licenseCity').itemList = cl;
      }
    },
    //初始化所在县市数据
    async initTown(customerCity) {
      if (!customerCity || customerCity == null || typeof customerCity == 'undefined') {
        return;
      }
      let td = this.cityData[customerCity].children;
      console.log('4444', td);
      let tl = this.createSubRegionList(td);
      this.initForm[8].itemList = tl;
    },
    async saveFile() {
      this.$refs.fileFormPanel.SUBMIT_FORM();

      if (this.formValue1 !== null) {
        if (this.formValue1.caseUrl.length == 0) {
          this.$notify.warning({ title: '提示信息', message: '请上传附件!' });
          return;
        }
        let list = [];
        for (let i = 0; i < this.formValue1.caseUrl.length; i++) {
          let map = {};
          let name = this.formValue1.caseUrl[i].name;
          let url = this.formValue1.caseUrl[i].url;
          map = Object.assign({}, { url: url }, map);
          map = Object.assign({}, { name: name }, map);
          list.push(map);
        }
        console.log(list);
        let res = {};
        res = await updateFile(list, this.projectId);
        if (res.resultCode === 200) {
          this.$notify.success({ title: '提示信息', message: '上传成功!' });
        } else {
          this.$notify.error({ title: '提示信息', message: '上传失败!' });
        }
        //let res = {};
        //if (this.type === 'add') {
        //res = await addMarketType(this.formValue);
        //}
        // if (this.type === 'edit') {
        //  res = await updateMarketType(this.formValue, this.recordId);
        // }
        //if (res.resultCode === 200) {
        //  this.closeDialog('refresh');
        //}
      }
    },
    //关闭详情
    closeContactInfo(val, type) {
      this.visibleContactInfo = false;
      if (type === 'refresh') {
        this.fetchParams = { ...this.fetchParams };
      }
    },
    addHandle() {
      this.handleType = 'add';
      this.title = '新增联系人信息';
      this.initData = {
        type: 'add' //add/edit/show
      };
      this.formData = { projectId: this.projectId };
      this.visibleContactInfo = true;
    },
    editHandle(row) {
      this.handleType = 'edit';
      this.title = '编辑联系人信息';
      console.log(row);
      this.initData = {
        type: 'edit' //add/edit/show
      };
      this.formData = row;
      this.visibleContactInfo = true;
    },
    async del(contactId) {
      this.$confirm('确定删除吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          this.res = await delcontact(contactId);
          console.log('232323232323-----------', this.res);
          if (this.res.resultCode != 200) {
            this.$notify.error({ title: '提示信息', message: res.errMsg || '删除失败!' });
          } else {
            this.$notify.success({ title: '提示信息', message: '删除成功!' });
            // 重新加载
            this.fetchParams = { ...this.fetchParams };
          }
        })
        .catch(() => {
          // this.$notify.info({title: '提示信息',message:'已取消删除'});
        });

      //this.res = await delcontact(contactId);
      //this.fetchParams = { ...this.fetchParams };
    },
    deleHandle(contactId) {
      this.del(contactId);
    },
    formatDates: function(value) {
      // 这里的 value 就是需要过滤的数据
      if (value == null || value == '') {
        return '';
      }
      var date = new Date(value);
      var year = date.getFullYear();
      var month = date.getMonth() + 1;
      var day = date.getDate();
      return year + '-' + month + '-' + day;
    },
    //table表头和数据源
    creatHeader() {
      return [
        {
          title: '操作',
          dataIndex: 'column-action',
          width: 100,
          fixed: 'left',
          render: props => {
            <el-button size="mini" type="text" onClick={() => this.deleHandle(props.row.contactId)}>
              删除
            </el-button>;
            return (
              <div>
                <el-button size="mini" type="text" onClick={() => this.editHandle(props.row)}>
                  编辑
                </el-button>
              </div>
            );
          }
        },
        {
          title: '序号',
          dataIndex: 'index',
          width: 80,
          sorter: true,
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },

        {
          title: '联系人类型',
          dataIndex: 'contactType',
          sorter: true,
          render: props => {
            return <span>{this.createDictText(props.row.contactType, '2517')}</span>;
          }
        },
        { title: '姓名', dataIndex: 'contactName', sorter: true },
        {
          title: '性别',
          dataIndex: 'contactSex',
          sorter: true,
          render: props => {
            return <span>{this.createDictText(props.row.contactSex, '1002')}</span>;
          }
        },
        { title: '职务', dataIndex: 'contactJob', sorter: true },
        { title: '手机', dataIndex: 'contactMobile', sorter: true },
        { title: '邮箱', dataIndex: 'contactEmail', sorter: true },
        {
          title: '出生日期',
          dataIndex: 'birthday',
          sorter: true,
          render: props => {
            return <span>{formatdateByDay(props.row.birthday)} </span>;
          }
        },
        { title: '家庭住址', dataIndex: 'homeAddress', sorter: true },
        { title: '个人喜好', dataIndex: 'hobby', sorter: true }
      ];
    },
    async saveDialog() {
      this.res = await propertyInfo(this.rowData.projectId);
      this.initLicenseProvince();
      console.log('Test1---->', this.res);
      this.init();
    },
    initRegion(customerProvince, customerCity) {
      this.initCity(customerProvince);
      this.initTown(customerCity);
    },
    //初始化数据
    init() {
      // console.log('行数据---->', this.value);
      console.log('是否编辑---->', this.infoBasic);
      console.log('数据---->', this.formData);
      let customerProvince, customerCity, licenseProvince;
      //赋值
      this.initForm.forEach(x => {
        x.initialValue = this.res.data[x.fieldName];
        if (x.fieldName === 'customerProvince') {
          customerProvince = this.res.data[x.fieldName];
        } else if (x.fieldName === 'customerCity') {
          customerCity = this.res.data[x.fieldName];
        } else if (x.fieldName === 'licenseProvinces') {
          licenseProvince = this.res.data[x.fieldName];
        }
      });
      this.initRegion(customerProvince, customerCity);
      this.initLicenseCity(licenseProvince);
      this.initForm2.forEach(x => {
        x.initialValue = this.res.data[x.fieldName];
      });
      this.initForm3.forEach(x => {
        x.initialValue = this.res.data[x.fieldName];
      });
      this.fileForm.forEach(x => {
        x.initialValue = this.res.data[x.fieldName];
      });
    },
    async initLicenseProvince(){
         if(this.res.data['isLicenseAll'] === 10041001){//是全国上牌
           this.isLicenseAll = true;
         }else{
          this.isLicenseAll = false;
         };
         let licenseProvince = this.res.data['licenseProvinces'];//上牌省份
          //上牌城市不可编辑
          let lpaInitArray = [];
          if(licenseProvince!=null && typeof(licenseProvince)!='undefined' && licenseProvince!=''){
             lpaInitArray = licenseProvince.split(",");
             if(lpaInitArray!=null && lpaInitArray.length>0){
               for(let k=0;k<lpaInitArray.length;k++){
                 lpaInitArray[k] = parseInt(lpaInitArray[k]);
               }
             }
          }
      this.res.data['licenseProvinces'] = lpaInitArray;
      },
    reloadInit() {
      alert(1);
      let customerProvince, customerCity, licenseProvince;
      //赋值
      this.initForm.forEach(x => {
        x.initialValue = this.res.data[x.fieldName];
        if (x.fieldName === 'customerProvince') {
          customerProvince = this.res.data[x.fieldName];
        } else if (x.fieldName === 'customerCity') {
          customerCity = this.res.data[x.fieldName];
        } else if (x.fieldName === 'licenseProvinces') {
          licenseProvince = this.res.data[x.fieldName];
        }
      });
      this.initRegion(customerProvince, customerCity);
      this.initLicenseCity(licenseProvince);
      this.fileForm.forEach(x => {
        x.initialValue = this.res.data[x.fieldName];
      });
    },
    //搜索数据
    initFormFun() {
      return [
        {
          type: 'INPUT',
          label: '客户公司名称',
          fieldName: 'customerName',
          style: { width: '150px' },
          initialValue: ''
        },
        {
          type: 'SELECT',
          label: '客户类型',
          fieldName: 'customerType',
          style: { width: '150px' },
          initialValue: '',
          itemList: this.createDictList('2506')
        },
        {
          type: 'SELECT',
          label: '客户性质',
          fieldName: 'customerProperty',
          style: { width: '150px' },
          initialValue: '',
          itemList: this.createDictList('2534')
        },
        {
          type: 'SELECT',
          label: '客户状态',
          fieldName: 'customerStatus',
          style: { width: '150px' },
          initialValue: '',
          itemList: this.createDictList('2507')
        },
        {
          type: 'SELECT',
          label: '客户来源',
          fieldName: 'customerSource',
          style: { width: '150px' },
          initialValue: '',
          itemList: this.createDictList('2508')
        },
        {
          type: 'DATE',
          label: '建档时间',
          fieldName: 'recordDate',
          valueFormat: 'yyyy-MM-dd',
          style: { width: '150px' },
          initialValue: ''
        },
        {
          type: 'SELECT',
          label: '省份',
          fieldName: 'customerProvince',
          style: { width: '150px' },
          initialValue: '',
          itemList: []
        },
        {
          type: 'SELECT',
          label: '市',
          fieldName: 'customerCity',
          style: { width: '150px' },
          initialValue: '',
          itemList: []
        },
        {
          type: 'SELECT',
          label: '县区',
          fieldName: 'customerDistrict',
          style: { width: '150px' },
          initialValue: '',
          itemList: []
        },
        {
						type: 'INPUT',
						label: '社会统一信用代码',
            fieldName: 'uniformSocialCreditCode',
            style: { width: '150px' },
						initialValue: '',
						placeholder:'',
				},
        {
          type: 'TEXT_AREA',
          label: '详细地址',
          fieldName: 'customerAddress',
          style: { width: '150px' },
          rows: 1,
          initialValue: ''
        },
        {
          type: 'SELECT',
          label: '客户等级',
          fieldName: 'customerLevel',
          style: { width: '150px' },
          rows: 1,
          initialValue: '',
          itemList: this.createDictList('2509')
        },
        {
          type: 'SELECT',
          label: '所属行业分类',
          fieldName: 'industryCategory',
          style: { width: '150px' },
          initialValue: '',
          itemList: this.createDictList('2510')
        },
        {
          type: 'SELECT',
          label: '行业地位',
          fieldName: 'industryStatus',
          style: { width: '150px' },
          initialValue: '',
          itemList: this.createDictList('2511')
        },
        {
          type: 'SELECT',
          label: '采购方式',
          fieldName: 'purchaseMode',
          style: { width: '150px' },
          initialValue: '',
          itemList: this.createDictList('2512')
        },
        {
          type: 'INPUT',
          label: '意向车型',
          fieldName: 'intentionModelName',
          style: { width: '150px' },
          initialValue: ''
        },
        {
          type: 'INPUT_NUMBER',
          label: '预计采购数量',
          fieldName: 'estimatePurchaseNum',
          style: { width: '150px' },
          initialValue: ''
        },
        {
          type: 'SELECT',
          label: '购车用途',
          fieldName: 'buyPurpose',
          style: { width: '150px' },
          initialValue: '',
          itemList: this.createDictList('2513')
        },
        {
          type: 'DATE',
          label: '预计采购日期',
          fieldName: 'estimatePurchaseDate',
          valueFormat: 'yyyy-MM-dd',
          style: { width: '150px' },
          initialValue: ''
        },
        {
          type: 'SELECT',
          label: '预算来源',
          fieldName: 'budgetSource',
          style: { width: '150px' },
          initialValue: '',
          itemList: this.createDictList('2514')
        },
        {
          type: 'INPUT_NUMBER',
          label: '年度预算',
          fieldName: 'yearBudget',
          style: { width: '150px' },
          initialValue: '',
          precision: 2
        },
        {
          type: 'SELECT',
          label:'是否全国上牌',
          fieldName:'isLicenseAll',
          style: { width: '150px' },
          initialValue: '',
          itemList: this.createDictList('1004')
        },
        {
          type: 'MULTIPLE_SELECT',
          label: '上牌省份',
          fieldName: 'licenseProvinces',
          style: { width: '150px' },
          initialValue: '',
          itemList: []
        },
        {
          type: 'SELECT',
          label: '上牌城市',
          fieldName: 'licenseCity',
          style: { width: '150px' },
          initialValue: '',
          itemList: this.createDictList('1008')
        },
        {
          type: 'SELECT',
          label: '是否跨区销售',
          fieldName: 'isCrossSbu',
          initialValue: '',
          style: { width: '150px' },
          itemList: this.createDictList('1004')
        },
        {
          type: 'INPUT',
          label: '融资渠道',
          fieldName: 'financeChannel',
          style: { width: '150px' },
          initialValue: ''
        },
        {
          type: 'INPUT',
          label: '客户关键联系人',
          style: { width: '150px' },
          fieldName: 'keyLinkMan',
          initialValue: ''
        },
        {
          type: 'INPUT',
          label: '联系方式',
          fieldName: 'linkPhone',
          style: { width: '150px' },
          initialValue: ''
        },
        {
          type: 'TEXT_AREA',
          label: '备注',
          fieldName: 'remark',
          style: { width: '150px' },
          rows: 2,
          initialValue: ''
        }
      ];
    },
    //搜索数据
    initFormFun2() {
      return [
        {
          type: 'INPUT',
          label: '项目名称',
          fieldName: 'projectName',
          initialValue: ''
        },
        {
          type: 'INPUT',
          label: '项目编号',
          fieldName: 'projectCode',
          initialValue: ''
        },
        {
          type: 'INPUT',
          label: '项目生效日期',
          fieldName: 'projectStartDate',
          initialValue: ''
        },
        // {
        //   type: 'INPUT',
        //   label: '项目生效日期',
        //   fieldName: 'projectEndDate',
        //   initialValue: ''
        // },
        {
          type: 'TEXT_AREA',
          label: '客户情况描述',
          fieldName: 'customerDesc',
          rows: 2,
          initialValue: ''
        },
        {
          type: 'TEXT_AREA',
          label: '项目背景',
          fieldName: 'projectBackgroud',
          rows: 2,
          initialValue: ''
        },
        {
          type: 'TEXT_AREA',
          label: '公司发展规划',
          fieldName: 'companyDevelopPlan',
          rows: 2,
          initialValue: ''
        },
        {
          type: 'TEXT_AREA',
          label: '车辆更新计划',
          fieldName: 'vehicleUpdatePlan',
          rows: 2,
          initialValue: ''
        },
        {
          type: 'TEXT_AREA',
          label: '融资需求',
          fieldName: 'financingNeeds',
          rows: 2,
          initialValue: ''
        },
        {
          type: 'TEXT_AREA',
          label: '其他重点采购说明',
          fieldName: 'otherDesc',
          rows: 2,
          initialValue: ''
        }
      ];
    },
    //搜索数据
    initFormFun3() {
      return [
        {
          type: 'INPUT',
          label: '竞品产品',
          fieldName: 'competingProduct',
          initialValue: ''
        },
        {
          type: 'INPUT',
          label: '竞品价格',
          fieldName: 'competingPrice',
          initialValue: ''
        },
        {
          type: 'TEXT_AREA',
          label: '竞品商务政策和服务',
          fieldName: 'competingPolicy',
          rows: 2,
          initialValue: ''
        },
        {
          type: 'TEXT_AREA',
          label: '竞品优劣势分析',
          fieldName: 'competingAnalyse',
          rows: 2,
          initialValue: ''
        }
      ];
    },
    //搜索数据
    fileFormFun() {
      return [
        {
          type: 'UPLOAD_FILE',
          label: '附件',
          disabled: this.type === 'show' ? true : false,
          fieldName: 'caseUrl',
          initialValue: '',
          upload: {
            actionUrl: '/api/file/oss/upload'
          },
          selfCols:2
        }
      ];
    },
    formChange(val) {
      this.formValue1 = val;
      console.log(val);
    },
    formChangeHandle(val) {
      this.formValue = val;
      console.log(val);
    },
    closeDialog(param) {
      this.$emit('close', false, param);
    }
  }
};
</script>
<style scoped>
.wrapper {
  height: calc(100vh - 110px);
}
</style>
